/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 */
package com.jeesite.modules.vehicle.web;

import com.alibaba.fastjson.JSONObject;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.general.utils.CosApiUtils;
import com.jeesite.modules.sys.entity.DictData;
import com.jeesite.modules.sys.utils.DictUtils;
import com.jeesite.modules.vehicle.entity.CarApi;
import com.jeesite.modules.vehicle.service.CarApiService;
import org.springframework.beans.factory.annotation.  Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 测试数据Controller
 * @author ThinkGem
 * @version 2018-04-22
 */
@Controller
@RequestMapping(value = "${adminPath}/vehicle/")
public class CarApiController extends BaseController {

    private DecimalFormat df = new DecimalFormat("0.00");

	@Autowired
	private CarApiService carApiService;

	/**
	 * 查询列表数据
	 */
	@RequestMapping(value = "findCarList")
	@ResponseBody
	public Page<CarApi> findCarList(CarApi carApi, HttpServletRequest request, HttpServletResponse response) {
		Page<Object> page = new Page<>(request, response);
		String queryType = Optional.ofNullable(carApi.getQueryType()).orElse("");
		carApi.setQueryType(null);
		if(queryType.contains("brand")){
			// 品牌查询，直接传入品牌id或品牌名称【brandId,brandName】
		}
		if(queryType.contains("priceRange")){
			carApi.setQueryType("priceRange");
			// 价格范围查询，queryInfo传入金额区间，例如 1000~2000
		}
		if(queryType.contains("carType")){
			// 车辆类型查询，直接传入汽车类型id或类型名称【typeId,typeName】，例如 跑车、轿车
		}
		queryType.replace("carType","");
		queryType.replace("priceRange","");
		queryType.replace("brand","");
		queryType.replaceAll(",,","");
		// 排序相关
		List<String> orderBy = new ArrayList<>();
		// 定义类型到排序字段的映射
		Map<String, String> typeToFieldMap = new HashMap<>();
		typeToFieldMap.put("heat", "a.view_count"); // 热度排序
		typeToFieldMap.put("latest", "a.update_date"); // 最新发布
		typeToFieldMap.put("depreciate", "a.price_spread"); // 降价
		// 按顺序处理查询类型
		Arrays.stream(queryType.split("\\s*,\\s*"))
				.map(String::trim).filter(typeToFieldMap::containsKey)
				.forEach(type -> orderBy.add(typeToFieldMap.get(type)));
		if(orderBy.size()>0){
			page.setOrderBy(orderBy.stream().collect(Collectors.joining(","))+" desc");
		}
		carApi.setPage(page);
		Page<CarApi> page1 = carApiService.findCarList(carApi);
		List<CarApi> list = page1.getList();
		for(int i=0;i<list.size();i++){
			list.get(i).setShowSellPrice(df.format(list.get(i).getSellPrice()/100));
			list.get(i).setCoverUrl(CosApiUtils.URL+list.get(i).getCoverUrl());
			list.get(i).setMerchantLogo(CosApiUtils.URL+list.get(i).getMerchantLogo());
		}
		return page1;
	}

	/**
	 * 查询车详情
	 * @param carId
	 * */
	@RequestMapping(value = "getCarDetail")
	@ResponseBody
	public String getCarDetail(String carId){
		return renderResult(Global.TRUE, text("获取成功！"), carApiService.getCarDetail(carId));
	}

	/**
	 * 查询车标签
	 * */
	@RequestMapping(value = "findDictList")
	@ResponseBody
	public String findDictList(){
		List<DictData> list = DictUtils.getDictList("h_car_label");
		List<Map> maps = new ArrayList<>();
		for(DictData data:list){
			Map map = new HashMap();
			map.put("value",data.getDictValue());
			map.put("label",data.getDictLabel());
			maps.add(map);
		}
		return renderResult(Global.TRUE, text("获取成功！"), maps);
	}

	/**
	 * 保存车信息
	 * */
	@RequestMapping(value = "saveCarInfo")
	@ResponseBody
	public JSONObject saveCarInfo(MultipartFile file, CarApi carApi){
		JSONObject res = new JSONObject();
		res.put("result","false");
		if(file != null){
			JSONObject files = CosApiUtils.uploadFile(file,"","car/"+carApi.getPrefix());
			if(files.getBoolean("result")){
				res.put("msg","图像上传错误，请稍后再试！");
				return res;
			}else {
				res.put("data",files.get("filePath"));
				if("c".equals(carApi.getImageType())){
					carApi.setCoverUrl(files.get("fileName2").toString());
					carApiService.save(carApi);
					res.put("foreignId", carApi.getCarId());
				}else{
					Map map = new HashMap();
					map.put("imageId", IdGen.nextId());
					map.put("foreignId", carApi.getForeignId());
					map.put("imageUrl", files.get("fileName2"));
					map.put("imageType", carApi.getImageType());
					map.put("createBy", carApi.getCreateBy());
					carApiService.insertImage(map);
				}
			}
		}
		res.put("result","true");
		res.put("msg","提交成功！");
		return res;
	}

	/**
	 * 下架车
	 * */
	@RequestMapping(value = "shelfCar")
	@ResponseBody
	public String shelfCar(CarApi carApi){
		carApiService.update(carApi);
		return renderResult(Global.TRUE, text("下架成功！"));
	}
}